﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProDivingAdmin2salmon14.View;
using System.Diagnostics;

namespace ProDivingAdmin2salmon14
{
    public partial class FormMain : Form, IFormMain
    {
        #region Private members
        private List<Image> dots = new List<Image>();
        private BackgroundWorker checkJudges = new BackgroundWorker();
        private BackgroundWorker checkJudgesScore = new BackgroundWorker();
        private BackgroundWorker clockWork = new BackgroundWorker();
        private List<Tuple<PictureBox, TextBox, Label>> judgeConnectionAndScore = new List<Tuple<PictureBox, TextBox, Label>>();
        private StartUpForm startUpForm = new StartUpForm();
        private DiverForm diverForm = new DiverForm();
        private AddDataForm addDataForm = new AddDataForm();
        private JudgeForm judgeForm = new JudgeForm();
        private Stopwatch stopWatch = new Stopwatch();
        private bool isTimer;
        #endregion

        public FormMain(StartUpForm startUpForm, DiverForm diverForm, AddDataForm addDataForm, JudgeForm judgeForm)
        {
            this.startUpForm = startUpForm;
            this.diverForm = diverForm;
            this.addDataForm = addDataForm;
            this.judgeForm = judgeForm;
            InitializeComponent();

            this.judgeConnectionAndScore.Add(new Tuple<PictureBox, TextBox, Label>(this.Judge1Connection, this.Judge1Score, this.Judge1Label));
            this.judgeConnectionAndScore.Add(new Tuple<PictureBox, TextBox, Label>(this.Judge2Connection, this.Judge2Score, this.Judge2Label));
            this.judgeConnectionAndScore.Add(new Tuple<PictureBox, TextBox, Label>(this.Judge3Connection, this.Judge3Score, this.Judge3Label));
            this.judgeConnectionAndScore.Add(new Tuple<PictureBox, TextBox, Label>(this.Judge4Connection, this.Judge4Score, this.Judge4Label));
            this.judgeConnectionAndScore.Add(new Tuple<PictureBox, TextBox, Label>(this.Judge5Connection, this.Judge5Score, this.Judge5Label));
            this.judgeConnectionAndScore.Add(new Tuple<PictureBox, TextBox, Label>(this.Judge6Connection, this.Judge6Score, this.Judge6Label));
            this.judgeConnectionAndScore.Add(new Tuple<PictureBox, TextBox, Label>(this.Judge7Connection, this.Judge7Score, this.Judge7Label));
            this.judgeConnectionAndScore.Add(new Tuple<PictureBox, TextBox, Label>(this.Judge8Connection, this.Judge8Score, this.Judge8Label));
            this.judgeConnectionAndScore.Add(new Tuple<PictureBox, TextBox, Label>(this.Judge9Connection, this.Judge9Score, this.Judge9Label));

            foreach (var judge in this.judgeConnectionAndScore) 
            {
                judge.Item1.MouseHover  += new EventHandler(OnJudgeLabelHover);
                judge.Item2.MouseHover += new EventHandler(OnJudgeLabelHover);
                judge.Item3.MouseHover += new EventHandler(OnJudgeLabelHover);
            }

            this.dots.Add(ProDivingAdmin2salmon14.Properties.Resources.RedDot1);
            this.dots.Add(ProDivingAdmin2salmon14.Properties.Resources.GreenDot);

            
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;

            this.checkJudges.DoWork += new DoWorkEventHandler(CheckJudgesWork);
            this.checkJudges.ProgressChanged += new ProgressChangedEventHandler(CheckJudgesProgress);
            this.checkJudges.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CheckJudgesWorkDone);

            this.checkJudgesScore.DoWork += new DoWorkEventHandler(CheckJudgesScoreWork);
            this.checkJudgesScore.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CheckJudgesScoreWorkDone);

            this.clockWork.WorkerReportsProgress = true;
            this.clockWork.DoWork += new DoWorkEventHandler(ClockWorkWork);
            this.clockWork.ProgressChanged += new ProgressChangedEventHandler(ClockWorkProgress);
            this.clockWork.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ClockWorkDone);

            //this.addDataForm.FormClosed += new FormClosedEventHandler(UpdateDataGrids);
            this.diverForm.FormClosed += new FormClosedEventHandler(UpdateDataGrids);

            this.checkJudges.WorkerSupportsCancellation = true;
            this.checkJudges.WorkerReportsProgress = true;

            this.dataGridViewDiveOrder.MultiSelect = false;

            this.checkJudgesScore.WorkerSupportsCancellation = true;

            this.NextDiveButton.Click += new EventHandler(OnNextDive);

            if (!checkJudges.IsBusy) 
            {
                checkJudges.RunWorkerAsync();
            }
            if (!clockWork.IsBusy) 
            {
                clockWork.RunWorkerAsync();
            }
            this.isTimer = false;
        }

        #region Click events

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("Do you want to save contest?", "Save before exiting?", MessageBoxButtons.YesNo);
            if (result == System.Windows.Forms.DialogResult.Yes)
            {
                this.saveContestToolStripMenuItem_Click(sender, e);
        }
            this.Close();
        }

        private void saveContestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (EventGetFilePath != null)
            {
                if (EventGetFilePath() == "")
                {
                    this.saveAsContestToolStripMenuItem_Click(sender, e);
                }
                else
                {
                    try
                    {
                        if (EventSaveContest != null)
                        {
                            if (EventGetContest != null)
                            {
                                EventSaveContest(EventGetFilePath(), EventGetContest());
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine("Error saving Contest");
                        Console.WriteLine(exc.Message);
                    }
                }
            }
            }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm about = new AboutForm();
            about.ShowDialog();
        }

        private void disqualifyInjureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.diverForm.ShowDialog();

            if (this.dataGridViewDiveOrder.CurrentRow.Cells["diveName"].Value.ToString().Contains("DISQ")) 
            {
                this.CurrentDiveNameLabel.ForeColor = Color.Red;
                this.CurrentDiveNameLabel.Text = this.dataGridViewDiveOrder.CurrentRow.Cells["diveName"].Value.ToString();
                NextDiveButton.PerformClick();
            }
        }

        private void addEditToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.addDataForm.ShowDialog(this);
        }

        private void saveAsContestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveAs = new SaveFileDialog();

            saveAs.OverwritePrompt = true;
            saveAs.Filter = "XML save files (*.xml)|*.xml";

            if (EventGetContestName != null) 
            {
                saveAs.FileName = EventGetContestName();
            }
            saveAs.ShowDialog(this);

            string filePath = saveAs.FileName;

            if (EventSetFilePath != null)
            {
                EventSetFilePath(filePath);
            }

            if (EventSaveContest != null)
            {
                if (EventGetContest != null)
                {
                    EventSaveContest(filePath, EventGetContest());
                }
            }

        }

        private void loadContestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Contest contest = new Contest(true);
            OpenFileDialog open = new OpenFileDialog();
            
            open.Filter = "XML save files (*.xml)|*.xml";

            DialogResult result = open.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK || result == System.Windows.Forms.DialogResult.Yes)
            {
                string filePath = open.FileName;

                if (EventLoadContest != null)
                {
                    contest = EventLoadContest(filePath);
                }

                if (EventSetContest != null)
                {
                    EventSetContest(contest);
                }

                if (EventGetAmountOfJudges != null)
                {
                    for (int i = EventGetAmountOfJudges(); i < 9; i++)
                    {
                        judgeConnectionAndScore[i].Item1.Hide();
                        judgeConnectionAndScore[i].Item2.Hide();
                        judgeConnectionAndScore[i].Item3.Hide();
                    }
                }
                this.dataGridViewDiveOrder.ReadOnly = true;
                this.dataGridViewDiveOrder.DataSource = new BindingList<DisplayDive>(EventGetDiverOrder());

                this.dataGridViewRanking.ReadOnly = true;
                this.dataGridViewRanking.DataSource = new BindingList<Diver>(EventGetDiverList());

                this.SetHeaderNames();

                this.SetNextAndCurrentDiver();

                this.disqualifyInjureToolStripMenuItem.Enabled = true;
                this.addEditToolStripMenuItem.Enabled = false;
                this.addEditToolStripMenuItem1.Enabled = false;
            }
        }

        private void GetJudgesIDsButton_Click(object sender, EventArgs e)
        {
            if (EventGetJudgeIDs != null)
            {
                string[] ids = new string[10];
                EventGetJudgeIDs(ids);
                string temp = "";
                foreach (var id in ids)
                {
                    temp += id + '\n';
                }
                MessageBox.Show(temp);
            }
        }
        private void newContestToolStripMenuItem_Click(object sender, EventArgs e)
        {

            System.Windows.Forms.DialogResult result = this.startUpForm.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                if (EventResetData != null)
                {
                    if (EventGetIsFemaleData != null)
                    {
                        if (EventGetMinAge != null)
                        {
                            if (EventGetDivingHeight != null)
                            {
                                if (EventGetJudges != null)
                                {
                                    if (EventGetJudgesPath != null)
                                    {
                                        if (EventGetDiversPath != null)
                                        {
                                            if (EventGetContestName != null)
                                            {
                                                this.Text = this.Text + " - " + EventGetContestName();
                                                EventResetData(EventGetIsFemaleData(), EventGetMinAge(), EventGetDivingHeight(), EventGetJudges(), EventGetDiversPath(), EventGetJudgesPath(), EventGetFilePath());
                                                for (int i = EventGetJudges(); i < 9; i++)
                                                {
                                                    judgeConnectionAndScore[i].Item1.Hide();
                                                    judgeConnectionAndScore[i].Item2.Hide();
                                                    judgeConnectionAndScore[i].Item3.Hide();
                                                }
                                                if (EventGetIsFemaleData())
                                                {
                                                    this.ContestSexLabel.Text = "Woman's";
                                                }
                                                else 
                                                {
                                                    this.ContestSexLabel.Text = "Men's";
                                                }
                                                this.ContestDivingHeightLabel.Text = EventGetDivingHeight().ToString() + "m";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (EventGetDiverOrder != null)
                {
                    this.dataGridViewDiveOrder.ReadOnly = true;
                    this.dataGridViewDiveOrder.DataSource = new BindingList<DisplayDive>(EventGetDiverOrder());

                    this.dataGridViewRanking.ReadOnly = true;
                    this.dataGridViewRanking.DataSource = new BindingList<Diver>(EventGetDiverList());


                    this.SetHeaderNames();
                    this.disqualifyInjureToolStripMenuItem.Enabled = true;
                    this.addEditToolStripMenuItem.Enabled = false;
                    this.addEditToolStripMenuItem1.Enabled = false;
                }
            }
        }

        private void OnNextDive(object sender, EventArgs e)
        {
            if (!isTimer) 
            {
                isTimer = true;
                stopWatch.Start();
            }
            if (!this.checkJudgesScore.IsBusy)
            {
                NextDiveButton.Enabled = false;
                if (this.SetNextAndCurrentDiver())
                {
                    if (EventNextDive != null && EventResetConnectedJudgesScore != null)
                    {
                        EventResetConnectedJudgesScore();
                        EventNextDive();
                    }
                    foreach (var judge in judgeConnectionAndScore) 
                    {
                        judge.Item2.Text = "0";
                    }
                    this.JudgeTotalScore.Text = "0";

                    checkJudgesScore.RunWorkerAsync();
                }
                else 
                {
                    MessageBox.Show(this, "Congratulations, contest done!", "Done!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
            }

            this.dataGridViewRanking.ReadOnly = true;
            this.dataGridViewRanking.DataSource = new BindingList<Diver>(EventGetDiverList());
            this.SetHeaderNames();
        }
        #endregion

        #region Events
        private void UpdateDataGrids(object sender, FormClosedEventArgs e)
        {
            if (EventGetDiverOrder != null && EventGetDiverList != null)
            {
                this.dataGridViewDiveOrder.DataSource = null;
                this.dataGridViewDiveOrder.DataSource = EventGetDiverOrder();

                this.dataGridViewRanking.DataSource = null;
                this.dataGridViewRanking.DataSource = new BindingList<Diver>(EventGetDiverList());

                this.SetHeaderNames();
            }
            if (sender is DiverForm)
            {
                try
                {
                    if (this.dataGridViewDiveOrder.CurrentRow.Cells["diveName"].Value.ToString().Contains("DISQ"))
                    {
                        this.NextDiveButton.Enabled = true;
                        this.NextDiveButton.Focus();
                        this.checkJudgesScore.CancelAsync();
                    }
                }
                catch (NullReferenceException ex) 
                {
                    System.Console.WriteLine(ex.InnerException.Message);
                }
            }
            
        }

        private void OnJudgeLabelHover(object sender, EventArgs e)
        {
            int judgeNo;
            ToolTip tip = new ToolTip();

            if (sender is Label) 
            {
                judgeNo = Int32.Parse((sender as Label).Text.Remove(0, 1));

                if (EventGetJudgeList != null)
                {
                    foreach (var judge in EventGetJudgeList())
                    {
                        if (judge.order == judgeNo - 1)
                        {
                            tip.SetToolTip((sender as Label), judge.fullName + Environment.NewLine + "ID: " + judge.ID.ToString());
                        }
                    }
                }
            }
            else if (sender is TextBox) 
            {
                judgeNo = Int32.Parse((sender as TextBox).Name.Remove(0, 5).Remove(1));

                if (EventGetJudgeList != null)
                {
                    foreach (var judge in EventGetJudgeList())
                    {
                        if (judge.order == judgeNo - 1)
                        {
                            tip.SetToolTip((sender as TextBox), judge.fullName + Environment.NewLine + "ID: " + judge.ID.ToString());
                        }
                    }
                }
            }
            else if (sender is PictureBox)
            {
                judgeNo = Int32.Parse((sender as PictureBox).Name.Remove(0, 5).Remove(1));

                if (EventGetJudgeList != null)
                {
                    foreach (var judge in EventGetJudgeList())
                    {
                        if (judge.order == judgeNo - 1)
                        {
                            tip.SetToolTip((sender as PictureBox), judge.fullName + Environment.NewLine + "ID: " + judge.ID.ToString());
                        }
                    }
                }
            }
        }

        private void CurrentDiveNameLabel_MouseHover(object sender, EventArgs e)
        {
            ToolTip tip = new ToolTip();
            tip.SetToolTip(this.CurrentDiveNameLabel, this.dataGridViewDiveOrder["diveName", EventGetDiveOrderCounter() - 1].Value.ToString());
        }

        private void CurrentDiverNameLabel_MouseHover(object sender, EventArgs e)
        {
            ToolTip tip = new ToolTip();
            tip.SetToolTip(this.CurrentDiverNameLabel, this.dataGridViewDiveOrder["diverName", EventGetDiveOrderCounter() - 1].Value.ToString());
        }

        private void NextDiverNameLabel_MouseHover(object sebder, EventArgs e)
        {
            if (this.NextDiverNameLabel.Text != "")
            {
                ToolTip tip = new ToolTip();
                tip.SetToolTip(this.NextDiverNameLabel, this.dataGridViewDiveOrder["diverName", EventGetDiveOrderCounter()].Value.ToString());
            }
        }
        #endregion

        #region BackgroundWorkers
        private void ClockWorkWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (true) 
            {
                worker.ReportProgress(0);
                System.Threading.Thread.Sleep(999);
            }
        }

        private void ClockWorkProgress(object sender, ProgressChangedEventArgs e)
        {
            ClockLabel.Text = DateTime.Now.ToLongTimeString();
            if (isTimer) 
            {
                TimerLabel.Text = stopWatch.Elapsed.Hours.ToString().PadLeft(2, '0') + ':' + stopWatch.Elapsed.Minutes.ToString().PadLeft(2, '0') + ':' + stopWatch.Elapsed.Seconds.ToString().PadLeft(2, '0');
            }
        }

        private void ClockWorkDone(object sender, RunWorkerCompletedEventArgs e)
        {
            System.Console.WriteLine("Clock thread done!");
        }

        private void CheckJudgesWorkDone(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true) 
            {
                System.Console.WriteLine("CheckJudges cancelled");
            }
            else if (!(e.Error == null))
            {
                System.Console.WriteLine("An error with CheckJudges occured");
            }
            else 
            {
                System.Console.WriteLine("CheckJudges complete!");
            }
        }

        private void CheckJudgesProgress(object sender, ProgressChangedEventArgs e) 
        {
            List<Judge> connectedJudgeList = (List<Judge>)e.UserState;
            if (e.ProgressPercentage == 0 && EventBroadcastIP != null) 
            {
                EventBroadcastIP();
                return;
            }   
            foreach (var judge in connectedJudgeList) 
            {
                if (judge.isConnected)
                {
                    judgeConnectionAndScore[judge.order].Item1.Image = dots[1];

                    try
                    {
                        if (judgeConnectionAndScore[judge.order].Item2.Text == "0")
                        {
                            this.JudgeTotalScore.Text = (float.Parse(this.JudgeTotalScore.Text) + judge.score).ToString();
                        }

                        if (EventCalculateScore != null && EventGetCurrentDiver != null && EventGetCurrentDive != null)
                        {
                            EventGetCurrentDiver().diveList[EventGetCurrentDive()].CalculateScore();
                            this.JudgeAwardedScore.Text = EventGetCurrentDiver().diveList[EventGetCurrentDive()].diveScore.ToString();
                        }
                    }
                    catch
                    {
                        System.Console.WriteLine("Hej string exept");
                    }
                    judgeConnectionAndScore[judge.order].Item2.Text = judge.score.ToString();
                }
                else 
                {
                    judgeConnectionAndScore[judge.order].Item1.Image = dots[0];
                    judgeConnectionAndScore[judge.order].Item2.Text = "DC";
                }
            }
        }

        private void CheckJudgesWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            int counter = 0;
            while (true)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    if (EventGetConnectedJudgeList != null) 
                    {
                        worker.ReportProgress(counter, EventGetConnectedJudgeList());
                    }
                    if (EventGetIsDone != null) 
                    {
                        //if (EventGetIsDone()) 
                        //{
                        //    worker.CancelAsync();
                        //}
                        }

                    counter++;
                    worker.ReportProgress(0);
                    System.Console.WriteLine("CheckJudges did a check");
                    System.Threading.Thread.Sleep(3000);
                }
            }
        }

        private void CheckJudgesScoreWorkDone(object sender, RunWorkerCompletedEventArgs e) 
        {
            if (e.Cancelled == true)
            {
                //MessageBox.Show(this, "Contest is done!", "Contest done");
                System.Console.WriteLine("CheckJudgesScore cancelled");
            }
            else if (!(e.Error == null))
            {
                System.Console.WriteLine("An error with CheckJudgesScore occured");
            }
            else
            {
                System.Console.WriteLine("CheckJudgesScore complete!");
                this.dataGridViewRanking.ReadOnly = true;
                this.dataGridViewRanking.DataSource = new BindingList<Diver>(EventGetDiverList());
                this.SetHeaderNames();
                if ((EventGetDiveOrderCounter()) == this.dataGridViewDiveOrder.RowCount)
                {
                    MessageBox.Show(this, "Congratulations, contest done!", "Done!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
                else 
                {
                NextDiveButton.Enabled = true;
                NextDiveButton.Focus();
            }
        }
        }

        private void CheckJudgesScoreWork(object sender, DoWorkEventArgs e) 
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            bool isBreak = false;

            while (!isBreak) 
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else 
                {
                    System.Threading.Thread.Sleep(3000);
                    if (EventGetIsNextDive != null)
                    {
                        isBreak = EventGetIsNextDive();
                    }
                }
            }
        }
        #endregion

        #region Private methods
        private void SetHeaderNames()
        {
            this.dataGridViewDiveOrder.Columns["diverName"].HeaderText = "Diver name";
            this.dataGridViewDiveOrder.Columns["orderNumber"].HeaderText = "Order";
            this.dataGridViewDiveOrder.Columns["diverNationality"].HeaderText = "Nationality";
            this.dataGridViewDiveOrder.Columns["diveCode"].HeaderText = "Dive code";
            this.dataGridViewDiveOrder.Columns["diveHeight"].HeaderText = "Dive height";
            this.dataGridViewDiveOrder.Columns["diveDificulty"].HeaderText = "DD";
            this.dataGridViewDiveOrder.Columns["diveName"].HeaderText = "Dive name";

            this.dataGridViewRanking.Columns["nationality"].HeaderText = "Nationality";
            this.dataGridViewRanking.Columns["fullName"].HeaderText = "Name";
            this.dataGridViewRanking.Columns["totalScore"].HeaderText = "Total score";
            this.dataGridViewRanking.Columns["isDisqualified"].HeaderText = "Disqualified";
            this.dataGridViewRanking.Columns["isInjured"].HeaderText = "Injured";

            this.dataGridViewRanking.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            this.dataGridViewDiveOrder.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            this.dataGridViewDiveOrder.Columns["diveName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            this.dataGridViewRanking.Columns["fullName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            

            
        }
        private void HighightDiveOrderRow()
        {
            if (EventGetDiveOrderCounter != null)
            {
                this.dataGridViewDiveOrder.Rows[EventGetDiveOrderCounter()].Selected = true;
            }
        }
        
        private bool SetNextAndCurrentDiver() 
        {
            try
            {
                this.CurrentDiverNameLabel.Text = this.dataGridViewDiveOrder["diverName", EventGetDiveOrderCounter()].Value.ToString();
              
                if (this.CurrentDiverNameLabel.Text.Length >= 16)
                {
                    this.CurrentDiverNameLabel.Text = this.CurrentDiverNameLabel.Text.Remove(14);
                    this.CurrentDiverNameLabel.Text = this.CurrentDiverNameLabel.Text.PadRight(16, '.');
                }

                this.CurrentDiverNationalityLabel.Text = this.dataGridViewDiveOrder["diverNationality", EventGetDiveOrderCounter()].Value.ToString();
                this.CurrentDiveCodeLabel.Text = this.dataGridViewDiveOrder["diveCode", EventGetDiveOrderCounter()].Value.ToString();
                this.CurrentDiveNameLabel.Text = this.dataGridViewDiveOrder["diveName", EventGetDiveOrderCounter()].Value.ToString();
                if (this.CurrentDiveNameLabel.Text == "DISQUALIFIED")
                {
                    this.CurrentDiveNameLabel.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    this.CurrentDiveNameLabel.ForeColor = System.Drawing.Color.White;
                }
                if (this.CurrentDiveNameLabel.Text.Length >= 24)
                {
                    this.CurrentDiveNameLabel.Text = this.CurrentDiveNameLabel.Text.Remove(21);
                    this.CurrentDiveNameLabel.Text = this.CurrentDiveNameLabel.Text.PadRight(24, '.');
                }

                this.CurrentDDLabel.Text = this.dataGridViewDiveOrder["diveDificulty", EventGetDiveOrderCounter()].Value.ToString();
                this.CurrentDiverOrderLabel.Text = this.dataGridViewDiveOrder["orderNumber", EventGetDiveOrderCounter()].Value.ToString();
            }
            catch (ArgumentOutOfRangeException) 
            {
                this.CurrentDiverNameLabel.Text = "";
                this.CurrentDiverNationalityLabel.Text = "";
                this.CurrentDiverOrderLabel.Text = "";
                this.CurrentDiveNameLabel.Text = "";
                this.CurrentDDLabel.Text = "";
                this.CurrentDiveCodeLabel.Text = "";
                return false;
            }

            try
            {
                this.NextDiverNameLabel.Text = this.dataGridViewDiveOrder["diverName", EventGetDiveOrderCounter()+1 ].Value.ToString();
                
                if (this.NextDiverNameLabel.Text.Length >= 16)
                {
                    this.NextDiverNameLabel.Text = this.NextDiverNameLabel.Text.Remove(13);
                    this.NextDiverNameLabel.Text = this.NextDiverNameLabel.Text.PadRight(16, '.');
                }
                this.NextDiverNationalityLabel.Text = this.dataGridViewDiveOrder["diverNationality", EventGetDiveOrderCounter()+1 ].Value.ToString();
                this.NextDiverDiveCodeLabel.Text = this.dataGridViewDiveOrder["diveCode", EventGetDiveOrderCounter()+1 ].Value.ToString();
                this.NextDiverDDLabel.Text = this.dataGridViewDiveOrder["diveDificulty", EventGetDiveOrderCounter()+1 ].Value.ToString();
                this.NextDiverOrderLabel.Text = this.dataGridViewDiveOrder["orderNumber", EventGetDiveOrderCounter()+1 ].Value.ToString();
                if (this.NextDiverDiveCodeLabel.Text == "DISQ")
                {
                    this.NextDiverDiveCodeLabel.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    this.NextDiverDiveCodeLabel.ForeColor = System.Drawing.Color.White;
                }
                
                    
                
            }
            catch (ArgumentOutOfRangeException) 
            {
                this.NextDiverNameLabel.Text = "";
                this.NextDiverNationalityLabel.Text = "";
                this.NextDiverDiveCodeLabel.Text = "";
                this.NextDiverDDLabel.Text = "";
                this.NextDiverOrderLabel.Text = "";
            }
            HighightDiveOrderRow();
            return true;
        }
        #endregion

        #region Public event declarations

        public event DelegateGetJudgeList EventGetJudgeList = null;

        public event DelegateDiveOrderCounterIncrement EventDiveOrderCounterIncrement = null;

        public event DelegateGetDiveOrderCounter EventGetDiveOrderCounter = null;

        public event DelegateBroadcastIP EventBroadcastIP = null;

        public event DelegateGetIsDone EventGetIsDone = null;

        public event DelegateGetIsNextDive EventGetIsNextDive = null;

        public event DelegateSendDive EventSendDive = null;

        public event DelegateGetDiverOrder EventGetDiverOrder = null;

        public event DelegateGetAmountOfJudges EventGetAmountOfJudges = null;

        public event DelegateGetConnectedJudgeList EventGetConnectedJudgeList = null;

        public event DelegateNextDive EventNextDive = null;

        public event DelegateDQDiver EventDQDiver = null;

        public event DelegateGetNextDiver EventGetNextDiver = null;

        public event DelegatGetCurrentDiver EventGetCurrentDiver = null;

        public event DelegateGetDiverList EventGetDiverList = null;

        public event DelegateGetCurrentDive EventGetCurrentDive = null;

        public event DelegateCalculateScore EventCalculateScore = null;

        public event DelegateCalculateAllDivers EventCalculateAllDivers = null;

        public event DelegateResetData EventResetData = null;

        public event DelegateGetIsFemaleData EventGetIsFemaleData = null;

        public event DelegateGetMinAge EventGetMinAge = null;

        public event DelegateGetJudges EventGetJudges = null;

        public event DelegateGetDivingHeight EventGetDivingHeight = null;

        public event DelegateGetJudgesPath EventGetJudgesPath = null;

        public event DelegateGetDiversPath EventGetDiversPath = null;

        public event DelegateSetFilePath EventSetFilePath = null;

        public event DelegateGetFilePath EventGetFilePath = null;

        public event DelegateSaveContest EventSaveContest = null;

        public event DelegateGetContest EventGetContest = null;

        public event DelegateLoadContest EventLoadContest = null;

        public event DelegateSetContest EventSetContest = null;

        public event DelegateGetJugeIDs EventGetJudgeIDs = null;

        public event DelegateResetConnectedJudgesScore EventResetConnectedJudgesScore = null;

        public event DelegateGetContestName EventGetContestName = null;

        #endregion

        private void addEditToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            judgeForm.ShowDialog();
        }

        public void ShowJudgeForm() 
        {
            if (EventGetAmountOfJudges != null)
            {
                MessageBox.Show(this, "Wrong amount of judges in file." + Environment.NewLine + "Need " + EventGetAmountOfJudges().ToString() + " judges, please modify!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                this.judgeForm.Show();
            }
        }
    }
}
